﻿
using AngleSharp.Io;
using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Services;
using RndMaterialDisposalService.Services.Interface;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Text.Json;
using Org.BouncyCastle.Bcpg;

namespace RndMaterialDisposalService.Controllers
{
    /// <summary>
    /// 主数据
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class TokenController : ControllerBase
    {

        private IConfiguration configuration;
        private readonly ITokenService tokenService;
        private readonly ILogger<TokenController> logger;
        private readonly IUserInfoService userInfoService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_tokenService"></param>
        /// <param name="_logger"></param>
        /// <param name="_userInfoService"></param>
        /// <param name="_configuration"></param>
        public TokenController(ITokenService _tokenService,
            ILogger<TokenController> _logger,
            IUserInfoService _userInfoService,
            IConfiguration _configuration)
        {
            configuration = _configuration;
            tokenService = _tokenService;
            logger = _logger;
            userInfoService = _userInfoService;
        }

        /// <summary>
        /// 获取Token
        /// 实际用post请求
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetToken")]
        public async Task<IActionResult> GetToken()
        {
            var userId = "zhangsan";  //从前端传过来的。如果是sso登陆，密码用固定的，因为各系统已经没有用密码了。
            var passWord = "133";
            if ("zhangsan".Equals(userId) && "133".Equals(passWord)) //实际从数据库读取校验
            {
                //过期时间 2小时  //Bearer 
                var expireTime = DateTime.Now.AddHours(2);
                var strToken = await tokenService.CreateToken(expireTime);
                
                return Ok(new { Token = $"Bearer {strToken}", ExpireTime = expireTime });
            }
            return Unauthorized("账号或密码错误！");
        }

        /// <summary>
        /// 获取企业微信Token
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetWeixinToken")]
        public async Task<IActionResult> GetWeixinToken()
        {
            var strToken = await tokenService.GetWeixinToken();

            return Ok(strToken);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="token"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet("GetWeixinEmployeeId")]
        public async Task<IActionResult> GetWeixinEmployeeId(string token,string code)
        {
            var url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
            var data = new { access_token = token, code = code };
            var result = await HttpHelper.PostAsync(url, JsonSerializer.Serialize(data));
            var employeeId = JObject.Parse(result)["UserId"]??"";

            var employeeInfo = await userInfoService.GetUserDetail(employeeId.ToString());
            var userInfo = await userInfoService.GetUserInfo(employeeInfo.UserId);
            return Ok(new { employeeInfo = employeeInfo, userInfo = userInfo });
        }
    }
}
